package com.kai.mqtt.auth.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.kai.mqtt.auth.entity.MqttUser;
import com.kai.mqtt.auth.mapper.MqttUserMapper;
import com.kai.mqtt.auth.service.IMqttUserService;
import com.kai.mqtt.cache.AccessTokenCache;
import com.kai.mqtt.data.PageResult;
import com.kai.mqtt.data.request.MqttUserLoginRequest;
import com.kai.mqtt.data.request.MqttUserRequest;
import com.kai.mqtt.data.request.PageMqttUserRequest;
import com.kai.mqtt.data.response.MqttUserResponse;
import com.kai.mqtt.enums.ErrorCodeEnum;
import com.kai.mqtt.enums.StateEnum;
import com.kai.mqtt.exception.BusinessException;
import com.kai.mqtt.util.LoginLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author weijk
 * @since 2024/8/15
 */
@Service
public class IMqttUserServiceImpl extends ServiceImpl<MqttUserMapper, MqttUser> implements IMqttUserService {

    /**
     * 校验用户名密码
     *
     * @param username 用户名
     * @param password 密码
     * @return true-成功，false-失败
     */
    @Override
    public Boolean checkValid(String username, String password) {
        MqttUser mqttUser = this.lambdaQuery()
                .eq(MqttUser::getUsername, username)
                .one();
        return Objects.nonNull(mqttUser) && Objects.equals(mqttUser.getPassword(), DigestUtils.md5DigestAsHex(password.getBytes()));
    }

    /**
     * 登录
     *
     * @param request 参数
     * @return accessToken
     */
    @Override
    public String login(MqttUserLoginRequest request) {
        MqttUser mqttUser = this.lambdaQuery()
                .eq(MqttUser::getUsername, request.getUsername())
                .one();
        if (Objects.isNull(mqttUser)) {
            throw new BusinessException(ErrorCodeEnum.USER_DOES_NOT_EXIST);
        }
        if (Objects.equals(mqttUser.getIsAdmin(), StateEnum.NO.getCode())) {
            throw new BusinessException(ErrorCodeEnum.NO_PERMISSION);
        }
        if (!Objects.equals(mqttUser.getPassword(), DigestUtils.md5DigestAsHex(request.getPassword().getBytes()))) {
            throw new BusinessException(ErrorCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        String accessToken = UUID.randomUUID().toString().replace("-", "");
        AccessTokenCache.saveToken(accessToken, request.getUsername());

        return accessToken;
    }

    /**
     * 登出
     *
     * @return 结果
     */
    @Override
    public Boolean logout() {
        AccessTokenCache.removeToken(LoginLocalUtil.getToken());
        return true;
    }

    /**
     * 分页查询用户列表
     *
     * @param request 参数
     * @return 用户列表
     */
    @Override
    public PageResult<MqttUserResponse> pageUser(PageMqttUserRequest request) {
        IPage<MqttUser> mqttUserIPage = this.lambdaQuery()
                .eq(StringUtils.hasText(request.getUsername()), MqttUser::getUsername, request.getUsername())
                .eq(Objects.nonNull(request.getIsAdmin()), MqttUser::getIsAdmin, request.getIsAdmin())
                .page(new Page<>(request.getPageIndex(), request.getPageSize()));

        List<MqttUser> mqttUsers = mqttUserIPage.getRecords();
        if (CollectionUtils.isEmpty(mqttUsers)) {
            return PageResult.success(Lists.newArrayList(), mqttUserIPage.getCurrent(), mqttUserIPage.getSize(), mqttUserIPage.getTotal());
        }

        List<MqttUserResponse> responses = mqttUsers.stream()
                .map(mqttUser -> {
                    MqttUserResponse response = new MqttUserResponse();
                    BeanUtils.copyProperties(mqttUser, response);

                    return response;
                }).toList();

        return PageResult.success(responses, mqttUserIPage.getCurrent(), mqttUserIPage.getSize(), mqttUserIPage.getTotal());
    }

    /**
     * 创建用户
     *
     * @param request 参数
     * @return 结果
     */
    @Override
    public Boolean createUser(MqttUserRequest request) {
        MqttUser mqttUser = new MqttUser()
                .setUsername(request.getUsername())
                .setPassword(request.getPassword())
                .setIsAdmin(request.getIsAdmin())
                .setCreateDatetime(LocalDateTime.now())
                .setUpdateDatetime(LocalDateTime.now());
        return this.save(mqttUser);
    }

    /**
     * 删除用户
     *
     * @param id id
     * @return 结果
     */
    @Override
    public Boolean deleteUser(Integer id) {
        return this.removeById(id);
    }
}
